// utils/ocrService.js
// OCR服务 - 图片文字识别

const OCR_CONFIG = {
  // 百度OCR API配置
  BAIDU_OCR: {
    API_KEY: '6s5ZtdoVrylE5x1hpkPr2PGY',
    SECRET_KEY: 'bD2rZ9HHLrNuE9cHZdO7lWQmejHpYPxx',
    TOKEN_URL: 'https://aip.baidubce.com/oauth/2.0/token',
    OCR_URL: 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic'
  }
};

class OCRService {
  constructor() {
    this.accessToken = null;
    this.tokenExpireTime = 0;
  }

  // 获取百度OCR访问令牌
  async getBaiduAccessToken() {
    const now = Date.now();
    
    // 如果token还没过期，直接返回
    if (this.accessToken && now < this.tokenExpireTime) {
      return this.accessToken;
    }

    try {
      const response = await new Promise((resolve, reject) => {
        wx.request({
          url: OCR_CONFIG.BAIDU_OCR.TOKEN_URL,
          method: 'POST',
          data: {
            grant_type: 'client_credentials',
            client_id: OCR_CONFIG.BAIDU_OCR.API_KEY,
            client_secret: OCR_CONFIG.BAIDU_OCR.SECRET_KEY
          },
          header: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          success: resolve,
          fail: reject
        });
      });

      if (response.data && response.data.access_token) {
        this.accessToken = response.data.access_token;
        // token有效期通常是30天，这里设置为29天
        this.tokenExpireTime = now + (29 * 24 * 60 * 60 * 1000);
        return this.accessToken;
      } else {
        throw new Error('获取访问令牌失败');
      }
    } catch (error) {
      console.error('获取百度OCR访问令牌失败:', error);
      throw error;
    }
  }

  // 调用百度OCR API进行文字识别
  async recognizeTextWithBaidu(base64Image) {
    try {
      const accessToken = await this.getBaiduAccessToken();
      
      const response = await new Promise((resolve, reject) => {
        wx.request({
          url: `${OCR_CONFIG.BAIDU_OCR.OCR_URL}?access_token=${accessToken}`,
          method: 'POST',
          data: {
            image: base64Image,
            language_type: 'CHN_ENG', // 中英文混合
            detect_direction: 'true', // 检测图像朝向
            paragraph: 'false', // 是否输出段落信息
            probability: 'false' // 是否返回识别结果中每一行的置信度
          },
          header: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          success: resolve,
          fail: reject
        });
      });

      if (response.data && response.data.words_result) {
        // 提取识别的文字
        const textLines = response.data.words_result.map(item => item.words);
        return {
          success: true,
          text: textLines.join('\n'),
          lines: textLines,
          rawData: response.data
        };
      } else {
        throw new Error('OCR识别失败');
      }
    } catch (error) {
      console.error('百度OCR识别失败:', error);
      return {
        success: false,
        error: error.message || 'OCR识别失败'
      };
    }
  }

  // 模拟OCR识别（用于测试）
  async mockOCRRecognition(base64Image) {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 2000));
    
    return {
      success: true,
      text: `1. 计算题：3 + 5 = 8
2. 填空题：北京是中国的___首都___
3. 选择题：下列哪个是质数？
   A. 4  B. 6  C. 7  D. 8
   答案：C
4. 解答题：小明有10个苹果，给了小红3个，还剩几个？
   答案：7个
5. 应用题：一个长方形的长是8cm，宽是5cm，求面积。
   答案：40平方厘米`,
      lines: [
        '1. 计算题：3 + 5 = 8',
        '2. 填空题：北京是中国的___首都___',
        '3. 选择题：下列哪个是质数？',
        '   A. 4  B. 6  C. 7  D. 8',
        '   答案：C',
        '4. 解答题：小明有10个苹果，给了小红3个，还剩几个？',
        '   答案：7个',
        '5. 应用题：一个长方形的长是8cm，宽是5cm，求面积。',
        '   答案：40平方厘米'
      ]
    };
  }

  // 解析识别的文本，提取题目和答案
  parseQuestions(ocrText) {
    const questions = [];
    const lines = ocrText.split('\n').filter(line => line.trim());
    
    let currentQuestion = null;
    let questionIndex = 0;

    for (let i = 0; i < lines.length; i++) {
      const line = lines[i].trim();
      
      // 检测题目开始（以数字开头）
      const questionMatch = line.match(/^(\d+)\.?\s*(.+)/);
      if (questionMatch) {
        // 保存上一个题目
        if (currentQuestion) {
          questions.push(currentQuestion);
        }
        
        questionIndex++;
        const questionText = questionMatch[2];
        
        // 判断题目类型
        let type = 'other';
        if (questionText.includes('计算') || questionText.includes('=') || /\d+\s*[+\-×÷]\s*\d+/.test(questionText)) {
          type = 'calculation';
        } else if (questionText.includes('___') || questionText.includes('填空')) {
          type = 'fill';
        } else if (questionText.includes('选择') || /[A-D]\./.test(questionText)) {
          type = 'choice';
        } else if (questionText.includes('解答') || questionText.includes('应用')) {
          type = 'solve';
        }
        
        currentQuestion = {
          id: questionIndex,
          type: type,
          question: questionText,
          studentAnswer: '',
          standardAnswer: '',
          options: []
        };
      } else if (currentQuestion) {
        // 检测选项（A. B. C. D.）
        const optionMatch = line.match(/^([A-D])\.?\s*(.+)/);
        if (optionMatch) {
          currentQuestion.options.push({
            label: optionMatch[1],
            text: optionMatch[2]
          });
        } else if (line.includes('答案：') || line.includes('答案:')) {
          // 提取答案
          const answerMatch = line.match(/答案[：:]\s*(.+)/);
          if (answerMatch) {
            currentQuestion.studentAnswer = answerMatch[1].trim();
          }
        } else {
          // 其他内容作为题目的补充
          currentQuestion.question += ' ' + line;
        }
      }
    }
    
    // 添加最后一个题目
    if (currentQuestion) {
      questions.push(currentQuestion);
    }
    
    return questions;
  }

  // 主要的OCR识别方法
  async recognizeText(base64Image, useMock = false) {
    try {
      let ocrResult;
      
      if (useMock) {
        // 使用模拟数据进行测试
        ocrResult = await this.mockOCRRecognition(base64Image);
      } else {
        // 使用真实的百度OCR API
        ocrResult = await this.recognizeTextWithBaidu(base64Image);
      }
      
      if (!ocrResult.success) {
        throw new Error(ocrResult.error);
      }
      
      // 解析题目
      const questions = this.parseQuestions(ocrResult.text);
      
      return {
        success: true,
        text: ocrResult.text,
        questions: questions,
        rawData: ocrResult
      };
    } catch (error) {
      console.error('OCR识别失败:', error);
      return {
        success: false,
        error: error.message || 'OCR识别失败'
      };
    }
  }
}

// 导出单例
const ocrService = new OCRService();
module.exports = ocrService;